package action;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.Comparator;
import java.util.List;
import java.util.Set;

import actionImpl.DataAction;
import comparetor.BirthComparetor;
import comparetor.IdComparetor;
import entity.Customer;
import processor.DataHandler;
import processor.impl.DataHandlerImpl;
import scanner.DataScanner;
import scanner.impl.DataScannerImpl;
import util.FileHelper;

public class DataProcessAction implements DataAction {
	private Comparator<Customer> comparator;
	private DataHandler dp;
	private DataScanner scanner;
	private Printer printer;

	public DataProcessAction() throws FileNotFoundException {
		super();
		this.scanner = new DataScannerImpl(new FileInputStream("data.txt"));
		printer = new Printer();
	}

	public boolean action(InputStream in, OutputStream out) throws IOException {

		BufferedReader reader = new BufferedReader(new InputStreamReader(in));
		String command = reader.readLine();
		if (command.startsWith("q")) {
			return false;
		}
		if (command.contains("birth")) {
			comparator = new BirthComparetor();
		} else {
			comparator = new IdComparetor();
		}
		List<Customer> list = scanner.scann();
		dp = new DataHandlerImpl(list);
		Set<Customer> set = dp.process(comparator);// 打印

		if (command.startsWith("c")) {
			out.write("Done write to file!!\r\n".getBytes());
			FileHelper.write(set, command);
			return true;
		} else if (command.startsWith("l")) {
			printer.print(set, out, command);
		} else {
			out.write("Command not right!!\r\n".getBytes());
		}

		return true;
	}

	public static void main(String[] args) throws Exception {
		// new DataProcessAction().action();
	}
}
